import React, { useState, useEffect, useRef } from 'react';
import { Button, Form, Input, Select, Col, Row, Tooltip, Table, Pagination, Modal, Radio, message } from 'antd';
import { SyncOutlined, SearchOutlined, PlusOutlined, EditOutlined, DeleteOutlined, ExclamationCircleOutlined, VerticalAlignBottomOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import { getListAPI, delAPI, getDetailAPI, addAPI, putAPI } from '@/api/modules/equipment/shebeifenzu';
import { getDictsApi } from '@/api/modules/system/dictData';
import { download } from '@/api';
import { pageDelJump } from '@/utils';
import { IshebeifenzuType, IshebeifenzuDetailType } from '@/type/modules/equipment/shebeifenzu';
import ColorBtn from '@/components/ColorBtn';
import { hasPermi } from '@/utils/auth';
import { IdictType } from '@/type/modules/system/sysDictData';
import { SysDeptSelect } from '@/views/system/dept';

const ShebeifenzuTable = () => {
  const [queryForm] = Form.useForm();
  const [addEditForm] = Form.useForm();
  const { confirm } = Modal;

  // 分页
  const [queryParams, setQueryParams] = useState<IshebeifenzuType>({ pageNum: 1, pageSize: 10 });
  // 列表数据
  const [dataList, setDataList] = useState({ count: 0, rows: [] as IshebeifenzuDetailType[] });
  // table loading
  const [loading, setLoading] = useState(true);
  // 新增编辑 model显隐
  const [isModalOpen, setIsModalOpen] = useState(false);
  // 新增编辑判断
  const [isAdd, setIsAdd] = useState(true);
  // 非单个禁用
  const [single, setSingle] = useState(true);
  // 非多个禁用
  const [multiple, setMultiple] = useState(true);
  // 保存table 选择的key
  const [selectKeys, setSelectKeys] = useState<React.Key[]>([]);
  //  table 后台使用的key
  const [rowKeys, setRowKeys] = useState('');
  // 控制搜索隐藏显示
  const [searchShow, setSearchShow] = useState(true);
  // 当前编辑的id
  const [currentId, setCurrentId] = useState<number>();

  useEffect(() => {
    try {
      const getDictsFn = async () => {};
      getDictsFn();
    } catch (error) {}
  }, []);

  // 查询列表
  const getList = async () => {
    try {
      const { data } = await getListAPI(queryParams);
      setDataList({ ...data.result });

      message.success('查询成功');
      setLoading(false);
    } catch (error) {}
  };

  useEffect(() => {
    getList();
  }, [queryParams]);

  // 搜索
  const searchQueryFn = () => {
    const form = queryForm.getFieldsValue();
    setQueryParams({
      pageNum: 1,
      pageSize: 10,
      ...form,
    });
  };

  // 重置
  const resetQueryFn = () => {
    queryForm.resetFields();
    setSelectKeys([]);
    setQueryParams({ pageNum: 1, pageSize: 10 });
  };

  // row-select
  const rowSelection = {
    selectedRowKeys: selectKeys,
    onChange: (selectedRowKeys: React.Key[]) => {
      if (!selectedRowKeys.length || selectedRowKeys.length > 1) {
        setSingle(true);
      } else {
        setSingle(false);
      }
      selectedRowKeys.length ? setMultiple(false) : setMultiple(true);
      setSelectKeys(selectedRowKeys);
      setRowKeys(selectedRowKeys.join(','));
    },
  };

  // 获取详情
  const handleEditForm = async (id: number) => {
    try {
      const { data } = await getDetailAPI(id);
      setCurrentId(id);
      setIsModalOpen(true);
      setIsAdd(false);
      addEditForm.setFieldsValue(data.result as unknown as IshebeifenzuDetailType);
    } catch (error) {}
  };

  // 表单提交
  const handleFormFinish = async (values: IshebeifenzuDetailType) => {
    let apiError = false;
    try {
      if (isAdd) {
        await addAPI({ ...values }).then(
          () => {
            message.success('新增成功');
          },
          () => (apiError = true),
        );
      } else {
        await putAPI({ ...values, tableId: currentId }).then(
          () => {
            message.success('修改成功');
          },
          () => (apiError = true),
        );
      }
    } catch (error) {}
    if (apiError) {
      return;
    }
    setIsModalOpen(false);
    addEditForm.resetFields();
    getList();
  };

  // 分页
  const onPagChange = async (pageNum: number, pageSize: number) => {
    const form = queryForm.getFieldsValue();   
    setQueryParams({ pageNum, pageSize,...form });
  };

  // 删除
  const delFn = (ids: string) => {
    confirm({
      icon: <ExclamationCircleOutlined />,
      content: `是否确认删除编号为"${ids}"的数据项？`,
      centered: true,
      async onOk() {
        try {
          const { data } = await delAPI(ids);
          message.success(data.message);
          pageDelJump(dataList.count, ids, queryParams, setQueryParams);
        } catch (error) {}
      },
    });
  };

  // table
  const columns = [
    {
      title: '编码',
      dataIndex: 'index',
      key: 'index',
      align: 'center',
      render: (text, record, index) => index + 1, // 渲染序号
    },
    {
      title: '分组名称',
      dataIndex: 'name',
      key: 'name',
      align: 'center',
    },
    // {
    //       title: '部门',
    //       dataIndex: 'deptId',
    //       key: 'deptId',
    //       align: 'center',
    //       },
    {
      title: '操作',
      key: 'operation',
      align: 'center',
      fixed: 'right',
      render: (_: any, record: IshebeifenzuDetailType) => (
        <div>
          <Button hidden={hasPermi('equipment:shebeifenzu:edit')} onClick={() => handleEditForm(record.tableId as number)} size="small" icon={<EditOutlined />} type="link">
            修改
          </Button>
          <Button hidden={hasPermi('equipment:shebeifenzu:remove')} size="small" icon={<DeleteOutlined />} type="link" onClick={() => delFn(String(record.tableId))}>
            删除
          </Button>
        </div>
      ),
    },
  ] as ColumnsType<IshebeifenzuDetailType>;

  // 按照 filed1 属性进行排序
  dataList.rows.sort((a, b) => a.filed1.localeCompare(b.filed1));

  // table 数据源
  const tableData = dataList.rows;

  return (
    <div className="app-container">
      <Row gutter={16}>
        <Col span={24}>
          <Form form={queryForm} hidden={!searchShow} layout="inline" className="leno-search">
            <Form.Item label="部门" name="deptId">
              <SysDeptSelect style={{ width: 240 }} placeholder="请输入部门" allowClear></SysDeptSelect>
            </Form.Item>
            <Form.Item label="分组名称" name="name">
              <Input style={{ width: 240 }} placeholder="请输入分组名称" allowClear onPressEnter={searchQueryFn} />
            </Form.Item>

            <Form.Item>
              <Button onClick={searchQueryFn} type="primary" icon={<SearchOutlined />}>
                搜索
              </Button>
            </Form.Item>
            <Form.Item>
              <Button onClick={resetQueryFn} icon={<SyncOutlined />}>
                重置
              </Button>
            </Form.Item>
          </Form>
          <Row gutter={16} className="mb10">
            <Col span={16} className="leno-btn">
              <Row gutter={8}>
                <Col>
                  <ColorBtn
                    hidden={hasPermi('equipment:shebeifenzu:add')}
                    icon={<PlusOutlined />}
                    onClick={() => {
                      setIsModalOpen(true);
                      setIsAdd(true);
                    }}
                  >
                    新增
                  </ColorBtn>
                </Col>
              </Row>
            </Col>
          </Row>
          <div className="leno-table">
            <Table columns={columns} dataSource={tableData} pagination={false} rowKey="tableId" size="middle" loading={loading}  />
            <Pagination className="pagination" onChange={onPagChange} total={dataList.count} showSizeChanger showQuickJumper current={queryParams.pageNum} showTotal={(total) => `共 ${total} 条`} />
          </div>

          {/* 添加 编辑 */}
          <Modal
            title={isAdd ? '添加设备分组' : '编辑设备分组'}
            open={isModalOpen}
            onOk={() => addEditForm.submit()}
            onCancel={() => {
              setIsModalOpen(false);

              addEditForm.resetFields();
            }}
          >
            <Form form={addEditForm} labelCol={{ span: 5 }} onFinish={handleFormFinish}>
              <Form.Item label="部门" name="deptId" hidden={false} rules={[{ required: true, message: '请输入部门!' }]}>
                <SysDeptSelect style={{ width: 240 }} placeholder="请输入部门" allowClear></SysDeptSelect>
              </Form.Item>
              <Form.Item label="分组名称" name="name" hidden={false} rules={[{ required: true, message: '请输入分组名称!' }]}>
                <Input placeholder="请输入分组名称" />
              </Form.Item>
            </Form>
          </Modal>
        </Col>
      </Row>
    </div>
  );
};



export default ShebeifenzuTable;
// 当前列表的下拉选组件
export function ShebeifenzuTableSelect(props: any) {
  const { queryParams = {}, style = {} } = props;
  const [list, listSet] = useState([]);
  useEffect(() => {
    try {
      const init = async () => {
        const { data } = await getListAPI({ pageNum: 1, pageSize: 999999, ...queryParams });
        // 对数组进行排序
        data.result.rows.sort((a, b) => a.filed1.localeCompare(b.filed1));
        const listData: any = data.result.rows.map((item) => 
          // 需要自己改label和value的取值
           ({
            // label: `${item.deptId}/${item.name}`, // TODO 将部门名称显示出来
            label: item.name,
            value: item.name,
          })
        );
        listSet(listData);
      };
      init();
    } catch (error) {}
  }, [queryParams.deptId]);
  const selectProps = {
    ...props
  }
  delete selectProps.queryParams
  return <Select style={{ width: 240, ...style }} placeholder="请选择" options={list} {...selectProps} />;
}
export async function shebeifenzuList() {
  const { data } = await getListAPI({ pageNum: 1, pageSize: 999999 });
  return { tableName: 'shebeifenzu_table', rows: data.result.rows };
}
